package template

import (
	"lao-a/models/model"
	"strings"
)

//Template 模板字典详情
type PageTemplate struct {
	model.TdPageTemplate `xorm:"extends"`
	Components           []Component
}

//GetPages 获取模板页面
func (m *DAO) GetPages(typeID string) ([]model.TdPageTemplate, error) {
	var pages []model.TdPageTemplate
	var err error
	if typeID == "" || typeID == "All" {
		err = m.db.Where("status=1").Find(&pages)
	} else {
		err = m.db.Where("type_id=?", typeID).And("is_private=0").And("status=1").Find(&pages)
	}
	return pages, err
}

//GetPagesByPage 分页获取模板字典
func (m *DAO) GetPagesByPage(typeID string, Page int, Pagenum int) ([]model.TdPageTemplate, error) {
	var pages []model.TdPageTemplate
	var err error
	if typeID == "" || typeID == "All" {
		err = m.db.Where("status=1").Limit(Pagenum, Page*Pagenum).Find(&pages)
	} else {
		err = m.db.Where("type_id=?", typeID).And("is_private=0").And("status=1").Limit(Pagenum, Page*Pagenum).Find(&pages)
	}
	return pages, err
}

//GetTemplateByID 根据模板ID获取模板字典
func (m *DAO) GetPageByTplID(tplID string) ([]PageTemplate, error) {
	var pages []PageTemplate
	sql := `SELECT  a.*
			FROM    td_page_template a
					INNER JOIN td_template_with_pages b ON a.page_id = b.page_id
			WHERE   b.tpl_id = '` + tplID + `' order by b.sort_no asc`

	err := m.db.Sql(sql).Find(&pages)
	if err != nil {
		return nil, err
	}
	for inx, page := range pages {
		components, err := m.GetComponentByPageID(page.PageId)
		if err != nil {
			return nil, err
		}
		page.Components = components
		pages[inx] = page
	}
	return pages, nil
}

//GetPagesByIds 根据页面id集合获取id信息
func (m *DAO) GetPagesByIds(pageids string) ([]PageTemplate, error) {
	var pages []PageTemplate
	sql := `SELECT  *
			FROM    td_page_template
			WHERE   page_id in ('` + strings.Replace(pageids, ",", "','", -1) + `')`

	err := m.db.Sql(sql).Find(&pages)
	if err != nil {
		return nil, err
	}
	for inx, page := range pages {
		components, err := m.GetComponentByPageID(page.PageId)
		if err != nil {
			return nil, err
		}
		page.Components = components
		pages[inx] = page
	}
	return pages, nil
}
